package com.ljx.blog.user.event.handler;

import com.ljx.blog.user.enums.TenantRoleEnum;
import com.ljx.blog.user.domain.entity.Role;
import com.ljx.blog.user.domain.entity.Tenant;
import com.ljx.blog.user.event.TenantSubmitEvent;
import com.ljx.blog.user.service.RoleService;
import com.ljx.blog.user.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.ArrayList;
import java.util.List;

@Component
public class TenantSubmitEventHandler {

    @Autowired
    private TenantService tenantService;

    @Autowired
    private RoleService roleService;

    @Async
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = TenantSubmitEvent.class, fallbackExecution = true)
    public void saveTenantRole(TenantSubmitEvent event) {
        Tenant tenant = tenantService.getById(event.getTenantId());
        String tenantCode = tenant.getCode();
        List<Role> roles = new ArrayList<>();
        roles.add(new Role(TenantRoleEnum.getAdminCode(tenantCode)));
        roles.add(new Role(TenantRoleEnum.getUserCode(tenantCode)));
        roleService.saveBatch(roles);
    }


}
